package cc.rengu.igas.route.common.dao.impl;

import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.dao.MultiDyncDataStaticMapper;
import cc.rengu.igas.route.common.entity.MultiDyncDataStatic;
import cc.rengu.jradp.mods.dbs.Database;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 多路比例动态数据统计表操作类
 *
 * @author xlz
 * @version 1.0
 * @date 2020-03-13
 */
public class MultiDyncDataStaticMapperImpl implements MultiDyncDataStaticMapper {
    private RgLogger rglog = RgLog.getLogger(this.getClass().getName());
    private String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.ROUTE_POOL_NAME);

    public MultiDyncDataStaticMapperImpl() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.ROUTE_POOL_NAME);
        }
    }

    @Override
    public List<MultiDyncDataStatic> getAllMultiDyncDataStatic() throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getAllMultiDyncDataStatic");
        if (StringUtil.isNullorEmpty(sqlStr)) {
            throw new Exception("获取数据操作SQL失败");
        }

        MultiDyncDataStatic multiDyncDataStatic = new MultiDyncDataStatic();

        List<Object> objectList = dbsUtil.dbsFetchLimitListData(sqlStr, multiDyncDataStatic, MultiDyncDataStatic.class);
        if (null == objectList || objectList.isEmpty()) {
            rglog.error("多路比例暂无统计数据!");
            return null;
        }
        return objectList.stream().map(item -> (MultiDyncDataStatic) item).collect(Collectors.toList());

    }

    @Override
    public int insertMultiDyncDataStatic(MultiDyncDataStatic multiDyncDataStatic) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "insertMultiDyncDataStatic");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, multiDyncDataStatic, null);
        if (0 != iReturnCode) {
            rglog.error("登记比例路由动态统计数据表失败,instId:<{}>,ruleId:<{}>,channelId:<{}>,machineId:<{}>",
                    multiDyncDataStatic.getInstId(), multiDyncDataStatic.getRuleId(), multiDyncDataStatic.getChannelId(), multiDyncDataStatic.getMachineId(), iReturnCode);
        }
        return iReturnCode;
    }

    @Override
    public int delMultiDyncDataStatic(String instId, int ruleId, String channelId, String machineId) throws Exception {
        MultiDyncDataStatic multiDyncDataStatic = new MultiDyncDataStatic();
        multiDyncDataStatic.setInstId(instId);
        multiDyncDataStatic.setRuleId(ruleId);
        multiDyncDataStatic.setChannelId(channelId);
        multiDyncDataStatic.setMachineId(machineId);
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "delMultiDyncDataStatic");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, multiDyncDataStatic, null);
        if (0 != iReturnCode) {
            rglog.error("删除比例路由动态统计数据表失败,instId:<{}>,ruleId:<{}>,channelId:<{}>,machineId:<{}>",
                    multiDyncDataStatic.getInstId(), multiDyncDataStatic.getRuleId(), multiDyncDataStatic.getChannelId(), multiDyncDataStatic.getMachineId(), iReturnCode);
        }
        return iReturnCode;
    }

    /**
     * 查询多路比例动态统计数据
     *
     * @param instId    法人机构号
     * @param ruleId    路由规则id
     * @param channelId 渠道编码
     * @param machineId 机器唯一id
     * @return
     * @throws Exception
     */
    @Override
    public MultiDyncDataStatic getMultiDyncDataStaticByPk(String instId, int ruleId, String channelId, String machineId) throws Exception {
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "getMultiDyncDataStaticByPk");
        if (StringUtil.isNullorEmpty(sqlStr)) {
            throw new Exception("获取数据操作SQL失败");
        }

        MultiDyncDataStatic multiDyncDataStatic = new MultiDyncDataStatic();
        multiDyncDataStatic.setInstId(instId);
        multiDyncDataStatic.setRuleId(ruleId);
        multiDyncDataStatic.setChannelId(channelId);
        multiDyncDataStatic.setMachineId(machineId);
        int iRetCode = dbsUtil.dbsExecuteSql(sqlStr, multiDyncDataStatic, multiDyncDataStatic);
        if (Database.DBS_SUCCESS == iRetCode) {
            return multiDyncDataStatic;
        } else if (Database.DBS_NOT_FOUND == iRetCode) {
            return null;
        } else {
            rglog.error("查询多路比例路由动态统计数据失败");
            throw new Exception("查询多路比例路由动态统计数据失败");
        }
    }

    /**
     * 设置动态统计数据为无效
     *
     * @param instId    法人机构号
     * @param ruleId    路由规则id
     * @param channelId 渠道编码
     * @param machineId 机器唯一id
     * @throws Exception 失败
     */
    @Override
    public void setMultiDyncDataInvalidByPk(String instId, int ruleId, String channelId, String machineId) throws Exception {
        updMultiDyncDataStatusByPk(instId, ruleId, channelId, machineId, SmartRouteParamConstant.NO);
    }

    /**
     * 设置动态统计数据为有效
     *
     * @param instId    法人机构号
     * @param ruleId    路由规则id
     * @param channelId 渠道编码
     * @param machineId 机器唯一id
     * @throws Exception 失败
     */
    @Override
    public void setMultiDyncDataValidByPk(String instId, int ruleId, String channelId, String machineId) throws Exception {
        updMultiDyncDataStatusByPk(instId, ruleId, channelId, machineId, SmartRouteParamConstant.YES);
    }

    /**
     * 设置当前多路比例规则的所有通道配额使用量，使用同一个事物
     *
     * @param multiDyncDataRuleArrayList 当前多路比例所有通道
     * @throws Exception 失败
     */
    @Override
    public void setMultiDyncDataUsedByPk(ArrayList<MultiDyncDataStatic> multiDyncDataRuleArrayList) throws Exception {
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updMultiDyncDataUsedByPk");
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        try {
            for (MultiDyncDataStatic multiDyncDataStatic : multiDyncDataRuleArrayList) {
                if (Database.DBS_SUCCESS != dbsUtil.dbsExecuteTransactionSql(sqlStr, multiDyncDataStatic, null)) {
                    throw new Exception("以主键更新多路比例动态统计数据的当前使用量失败");
                }
            }
            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            throw e;
        }
    }

    private void updMultiDyncDataStatusByPk(String instId, int ruleId, String channelId, String machineId, String status) throws Exception {
        MultiDyncDataStatic multiDyncDataStatic = new MultiDyncDataStatic();
        multiDyncDataStatic.setInstId(instId);
        multiDyncDataStatic.setRuleId(ruleId);
        multiDyncDataStatic.setChannelId(channelId);
        multiDyncDataStatic.setMachineId(machineId);
        multiDyncDataStatic.setChannelStatus(status);
        multiDyncDataStatic.setChannelRealStatus(status);
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        String sqlStr = (String) UnifiedCache.get(AppParamConstant.SQL_MAPPER_CACHE, "updMultiDyncDataStatusByPk");
        int iReturnCode = dbsUtil.dbsExecuteSql(sqlStr, multiDyncDataStatic, null);
        if (0 != iReturnCode) {
            rglog.error("更新比例路由动态统计数据表失败,instId:<{}>,ruleId:<{}>,channelId:<{}>,machineId:<{}>",
                    multiDyncDataStatic.getInstId(), multiDyncDataStatic.getRuleId(), multiDyncDataStatic.getChannelId(),
                    multiDyncDataStatic.getMachineId(), iReturnCode);
            throw new Exception("更新比例路由动态统计数据表失败");
        }
    }
}
